//
//  PannelVC.swift
//  AG
//
//  Created by zhuxuhong on 2020/10/21.
//  Copyright © 2020 AgoCulture. All rights reserved.
//

import BWUIKit
import UIKit
import BWToolKit

open class PannelVC: ViewController {
    @IBOutlet open weak var closeBtn: UIButton!{
        didSet{
            closeBtn?.addTarget(self, action: #selector(closeBtnTapped), for: .touchUpInside)
        }
    }
    @IBOutlet weak var panelView: UIView! {
        set{
            _panelView = newValue
            _wrapperView.frame = newValue.frame
        }
        get{
            return _panelView
        }
    }
    open var panelSize: CGSize {
        get {
            return panelView.bounds.size
        }
        set{
            var rect = _wrapperView.frame
            rect.size = newValue
            _wrapperView.frame = rect
            _panelView.frame = _wrapperView.bounds
        }
    }
    
    private lazy var _panelView: UIView = {
        let v = UIView()
        v.backgroundColor = v.tintColor
        return v
    }()
    
    private lazy var _wrapperView: UIView = {
        let v = UIView()
        v.isUserInteractionEnabled = true
        v.backgroundColor = .clear
        return v
    }()
    
    /// 点击蒙层关闭
    public var canMaskTouchedDismissable = true
    
    public var isShowing = false {
        didSet{
            guard isShowing else {
                return
            }
            showCompletion?()
        }
    }
    private var showCompletion: BlockVoid?
    public var maskColor = UIColor.black.withAlphaComponent(0.3){
        didSet{
            view?.backgroundColor = maskColor
        }
    }
    
    open override var shouldAutorotate: Bool {
        return true
    }
    
    public init(panelView: UIView) {
        self.init()
        _panelView = panelView
    }
    
    public init(panelView: UIView, panelSize: CGSize) {
        self.init()
        _panelView = panelView
        self.panelSize = panelSize
    }
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    open override func didInit() {
        super.didInit()
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
    }
    
    open override func didLoad() {
        super.didLoad()
        
        view.alpha = 0
        view.backgroundColor = maskColor
        
        makeWrapperView()
    }
    
    open override func didRotated(previousTrait: UITraitCollection?, currentTrait: UITraitCollection) {
        guard isShowing else {
            return
        }
        updateWrapperView(_wrapperView)
    }
    
    private func makeWrapperView() {
        if panelView.translatesAutoresizingMaskIntoConstraints {
            panelView.frame = _wrapperView.bounds
            panelView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            panelView.removeFromSuperview()
            _wrapperView.addSubview(panelView)
        }
        else {
            let superView = panelView.superview
            superView?.constraints
                .filter{
                    ($0.firstItem as? UIView) == panelView ||
                    ($0.secondItem as? UIView) == panelView
                }
                .forEach{ superView?.removeConstraint($0) }
            panelView.removeFromSuperview()
            _wrapperView.addSubview(panelView)
            panelView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        view.addSubview(_wrapperView)
    }
    
    open override func didAppear() {
        super.didAppear()
        
        guard !isShowing else { return }
        
        setupWrapperView(_wrapperView)
        
        animate(for: _wrapperView)
    }
    
    @objc private func closeBtnTapped() {
        close()
    }
    
    open override func touchBegan(touch: UITouch) {
        super.touchBegan(touch: touch)
        guard canMaskTouchedDismissable,
              touch.view == view else {
                  return
              }
        close()
    }
    
    @IBAction func closePannel(_ sender: Any){
        close()
    }
    public func close(_ completion: BlockVoid? = nil) {
        animate(in: false, for: _wrapperView) { [weak self] in
            self?.dismiss(animated: false, completion: completion)
        }
    }
    public func show(_ completion: BlockVoid? = nil) {
        showCompletion = completion
        Jumper.jump(.present(self, animated: false, style: .overFullScreen, completion: nil))
    }
    
    /// 子类重写，实现自定义初始`frame`
    open func setupWrapperView(_ wrapperView: UIView) {
        fatalError("You must override this method for your customized frames!")
    }
    /// 子类重写，实现自定义动画后`frame`
    open func updateWrapperView(_ wrapperView: UIView) {
    }
    
    /// 子类重写，实现自定义动画
    open func animate(in isIn: Bool = true, for wrapperView: UIView, completion: (()->Void)? = nil) {
        fatalError("You must override this method for your customized animations!")
    }
}
